package com.ruoyi.web.controller.business.rule.factory;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.rule.domain.JbCustomerTypeNumberContentJson;
import com.ruoyi.business.rule.domain.JbOrderCoefficientRules;
import com.ruoyi.business.rule.domain.JbRules;
import com.ruoyi.business.rule.service.JbRulesService;
import com.ruoyi.common.annotation.JoException;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.controller.business.statistics.vo.JbCommissionCoefficientVO;
import com.ruoyi.web.controller.business.statistics.vo.JbRoyaltiesJSON;
import com.ruoyi.web.core.JoController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务 规则 工厂类
 *
 * @author Jyl
 */
@Component
public class JbRulesFactory extends JoController
{
    @Autowired
    private JbRulesService jbRulesService;
    @Autowired
    private JbOrderCoefficientRulesFactory jbOrderCoefficientRulesFactory;

    /**
     * 逻辑 获取 订单相关系数
     *
     * @return
     */
    public JbCommissionCoefficientVO fnCommissionCoefficient(Long orderId)
    {
        JbOrderCoefficientRules jbOrderCoefficientRules = jbOrderCoefficientRulesFactory.findByDeptAncestors(orderId);
        if (ObjectUtil.isEmpty(jbOrderCoefficientRules))
        {
            throw new ServiceException("缺少部门规则信息或登录用户信息！");
        }
        JbCommissionCoefficientVO jbCommissionCoefficientVO = new JbCommissionCoefficientVO();
        BeanUtils.copyProperties(jbOrderCoefficientRules, jbCommissionCoefficientVO);
        jbCommissionCoefficientVO.setCoefficientOfGiveaway(jbOrderCoefficientRules.getCoefficientGiveaway());
        return jbCommissionCoefficientVO;
    }

    /**
     * 获取 提成统一计算规则
     *
     * @return
     */
    private JbRoyaltiesJSON fnJbroyltiesJSON()
    {
        //查询规则
        JbRules jbRules = jbRulesService.getOne(new LambdaQueryWrapper<JbRules>().eq(JbRules::getRulesCode,
                "royalties"));
        JbRoyaltiesJSON jbRoyaltiesJSON = JSONObject.parseObject(jbRules.getExecutionContent().toString(),
                JbRoyaltiesJSON.class);
        return jbRoyaltiesJSON;
    }

    /**
     * @param grossProfitMargin 毛利率
     * @param orderAmount       订单金额
     * @param goodsAmount       商品金额 承担商品自己的承担系数
     * @param premiumPrice      溢价金额
     * @param giftAmount        赠品金额
     * @param isGift            是否有赠品
     * @param orderId           订单主键
     * @return 提成
     */
    @JoException(message = "提成计算异常！")
    public JSONObject fnRoyalties(BigDecimal grossProfitMargin,
                                  BigDecimal orderAmount,
                                  BigDecimal goodsAmount,
                                  BigDecimal premiumPrice,
                                  BigDecimal giftAmount,
                                  Boolean isGift,
                                  Long orderId
    )
    {
        JbRoyaltiesJSON jbRoyaltiesJSON = fnJbroyltiesJSON();
        JbCommissionCoefficientVO jbCommissionCoefficientVO = fnCommissionCoefficient(orderId);

        logger.info("{}>{}>{}", "订单提成计算(Order commission calculation)", premiumPrice,
                jbCommissionCoefficientVO.toString());

        //计算溢价金额
        premiumPrice = premiumPrice.multiply(jbCommissionCoefficientVO.getCommodityPremium())
                .divide(BigDecimal.valueOf(100.00), 2, RoundingMode.HALF_UP);
        Boolean isCanGift = grossProfitMargin.compareTo(jbCommissionCoefficientVO.getGrossProfitRate()) >= 0;
        JSONObject vo = new JSONObject().fluentPut("isCanGift", isCanGift);

        if (!isGift)
        {//没有赠品 ，提成=商品销售单价*商品提成比率，分成=溢价*分成比率
            return vo.fluentPut("commissionAmount", goodsAmount.setScale(2, RoundingMode.HALF_UP))
                    .fluentPut("premiumAmount", premiumPrice.setScale(2, RoundingMode.HALF_UP));
        }

        if (grossProfitMargin.compareTo(jbCommissionCoefficientVO.getGrossProfitRate()) < 0)
        { //订单毛利率小于毛利率分界线， 根据毛利率比率获取 提成比率； 提成=订单金额*提成比率， 分成=0
            for (JbRoyaltiesJSON.Ratio ratico : jbRoyaltiesJSON.getOrderRatio())
            {
                BigDecimal endValue = new BigDecimal(String.valueOf(ratico.getEndValue()));
                BigDecimal startValue = new BigDecimal(String.valueOf(ratico.getStartValue()));
                BigDecimal ratioValue = new BigDecimal(String.valueOf(ratico.getRatioValue()));

                if (endValue.compareTo(grossProfitMargin) > 0 && startValue.compareTo(grossProfitMargin) < 0)
                {//获取匹配规则 订单金额*订单提成比率-赠品承担系数
                    return vo.fluentPut("commissionAmount", orderAmount//订单金额
                                    .multiply(ratioValue)//提成系数
                                    .divide(BigDecimal.valueOf(100.00), 2, RoundingMode.HALF_UP)//降百分比
                            )
                            .fluentPut("premiumAmount", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
                }
            }
        } else
        {//订单毛利率 大于 毛利率分界线 有赠品， 提成=商品销售单价*商品提成比率-赠品承担金额，分成=溢价*分成比率
            return vo.fluentPut("commissionAmount", goodsAmount//商品金额
                            .subtract(giftAmount//赠品金额
                                    .multiply(jbCommissionCoefficientVO.getCoefficientOfGiveaway())//赠品承担系数
                                    .divide(BigDecimal.valueOf(100.00), 2, RoundingMode.HALF_UP))//减去赠品承担
                            .setScale(2, RoundingMode.HALF_UP))
                    .fluentPut("premiumAmount", premiumPrice.setScale(2, RoundingMode.HALF_UP));
        }

        return vo.fluentPut("commissionAmount", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP))
                .fluentPut("premiumAmount", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
    }

    /**
     * 编辑
     *
     * @param jbRules 规则对象
     * @return 执行结果
     */
    public boolean edit(JbRules jbRules)
    {
        if (Constants.DEPT_HIGHSEAS_ALLOCATION.equals(jbRules.getRulesCode()))
        {
            fnJbRules(jbRules);
        }
        return jbRulesService.updateInfoById(jbRules);
    }

    /**
     * 映射数据实体
     *
     * @param jbRules 规则对象
     * @return 执行结果
     */
    protected void fnJbRules(JbRules jbRules)
    {
        JSONObject jsonObject = jbRules.getExecutionContent();

        Map<String, Integer> map = new HashMap<>();
        JSONArray jsonArray = jsonObject.getJSONArray("userTypeCustomerList");
        List<JbCustomerTypeNumberContentJson> list = BeanUtil.copyToList(jsonArray,
                JbCustomerTypeNumberContentJson.class);
        for (JbCustomerTypeNumberContentJson item : list)
        {
            map.put(item.getUserTypeCode(), item.getUserNumber());
        }

        System.err.println("fnJbRules=========" + map.toString());
        jsonObject.put("peasantNumber", map.get("1003"));
        jsonObject.put("tradesmanNumber", map.get("1002"));
        jsonObject.put("dealerNumber", map.get("1001"));
    }
}
